class WorkerController < ApplicationController
  before_filter :sys_before_log

  def getAllWorkers
    name = params[:query] || ''
    #这种情况一般是抓取所有数据，如Combobox直接下拉或直接显示列表
    if params[:worker_id].nil? || params[:worker_id] == ""
      #如果有start说明是列表中抓取数据。否则是combobx，当然也有combobx分页的，但这儿没有给combobox分布。
      if params[:start].nil?
        workers = Worker.where("name like ? OR number like ?","%#{name}%","%#{name}%").order("team_id")
        workerCount = workers.length
      else
        #workers = Worker.where("name like ? OR number like ?","%#{name}%","%#{name}%").limit(params[:limit].to_i).offset(params[:start].to_i)
        workers = Worker.where("name like ? OR number like ?","%#{name}%","%#{name}%").order("team_id")
        workerCount = workers.length
        workers = workers.limit(params[:limit].to_i).offset(params[:start].to_i)
      end
    else
      #这种情况一般是在Combobox中输入了确定的某个人，然后搜索出来的。
      workers = Worker.where("id = ?",params[:worker_id]).order("team_id")
      workerCount = workers.length
    end
    jsonStr = "{worker:"+workers.to_json(:include => [:team])+",total:"+workerCount.to_s+"}"
    logger.info jsonStr
    render :text => jsonStr,:layout => false
  end

  #不取已经锁定的员工
  def getWorkersByTeam
    total = Worker.countWorkersByTeam params[:teamId]
    workers = Worker.findWorkersByTeam params[:teamId],params[:start].to_i.to_i,params[:limit].to_i.to_i
    jsonStr="{worker:"+workers.to_json+",total:"+total.to_s+"}"
    render :text => jsonStr,:layout => false
  end

  #获取指定组队的人员信息
  def getWorkersOfTeam
    total = Worker.count(:conditions=>['team_id = ?',params[:teamId].to_s])
    workers = Worker.find(:all,:conditions=>['team_id = ?',params[:teamId.to_s]])
    jsonStr = "{worker:"+workers.to_json()+",total:"+total.to_s+"}"
    render :text => jsonStr,:layout => false
  end

  def create
    begin
      worker = Worker.find_by_name params[:name]
      if worker != nil
        info = '员工名已存在，请更换！'
      else
        worker = Worker.new
        worker.name = params[:name]
        worker.team_id = params[:team_id]
        worker.number = params[:number]
        worker.save!
        info = 'success'
      end
    rescue Exception => e
      logger.info e
      info = '创建异常'
    end

    result = "{success:true,info:\"#{info}\"}"
    render :text => result,:layout => false
  end

  #锁定或解锁，只允许锁定。
  def doLock
    ids= params[:id][1..params[:id].length-2].split(',')
    for id in ids
      worker = Worker.find(id)
      if worker.is_locked == 1
        worker.is_locked = 0
      else
        worker.is_locked = 1
      end
      worker.save!
    end
    info = "success"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def edit
    worker = Worker.find(params[:workerId],:include=>[:team])
    jsonStr = worker.to_json(:include=>{:team=>{:only=>[:id,:name]}})
    render :text=>jsonStr,:layout=>false
  end

  def update
    begin
      worker = Worker.find(params[:id])
      #判断姓名是否重复
      if worker.name == params[:name].to_s
        #判断编号是否重复
        if worker.number.to_s == params[:number].to_s
          worker.team_id = params[:team_id]
          worker.save
          info = 'success'
        else
          worker1 = Worker.find_by_number params[:number]
          if worker1 == nil
            worker.team_id = params[:team_id]
            worker.number = params[:number]
            worker.save
            info = 'success'
          else
            info = '该编号已存在，请更换！'
          end
        end
        
      else
        workerUser = Worker.find_by_name params[:name]
        if workerUser == nil
          if worker.number.to_s == params[:number].to_s
            worker.team_id = params[:team_id]
            worker.name = params[:name]
            worker.save
            info = 'success'
          else
            worker1 = Worker.find_by_number params[:number]
            if worker1 == nil
              worker.team_id = params[:team_id]
              worker.number = params[:number]
              worker.name = params[:name]
              worker.save
            else
              info = '该编号已存在，请更换！'
            end
          end
        else
          info = '该账号已存在，请更换！'
        end
      end
    rescue Exception=>e
      logger.info e
      info = '更新异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end

  require "spreadsheet"

  def printWorker
    Spreadsheet.client_encoding = "UTF-8"
    bookString = StringIO.new
    book = Spreadsheet.open "#{Rails.root.to_s}/public/report_template/worker_template.xls"
    workers = Worker.all
    i = 1

    sheet1 = book.worksheet 0
    workers.each do |worker|
      sheet1[i,0] = worker.name
      sheet1[i,1] = worker.number
      sheet1[i,2] = worker.team ? worker.team.name : '未设置'
      i += 1
    end
    book.write bookString
    send_data bookString.string,:filename => 'worker.xls'
  end

end
